/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uy.edu.ort.arqsw.util;

import java.security.GeneralSecurityException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class UtilEncriptador {
    Cipher ecipher;
    Cipher dcipher;
    String textoclave = "claveencriptacion";

    UtilEncriptador() throws CriptException {
        try {
            byte[] salt = {
                (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
                (byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
            };

            int contadorIteraciones = 19;

            KeySpec keySpec = new PBEKeySpec(textoclave.toCharArray(), salt, contadorIteraciones);
            SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);

            ecipher = Cipher.getInstance(key.getAlgorithm());
            dcipher = Cipher.getInstance(key.getAlgorithm());

            AlgorithmParameterSpec param_spec = new PBEParameterSpec(salt, contadorIteraciones);

            ecipher.init(Cipher.ENCRYPT_MODE, key, param_spec);
            dcipher.init(Cipher.DECRYPT_MODE, key, param_spec);
        } catch (GeneralSecurityException exc) {
            UtilLog.log.error(exc.getStackTrace());
            throw new CriptException();
        }
    }

    public String encriptar(String cadena) throws CriptException {
       try {
            byte[] utf8 = cadena.getBytes("UTF8");

            byte[] encoder = ecipher.doFinal(utf8);

            return new sun.misc.BASE64Encoder().encode(encoder);
       } catch (Exception exc) {
            UtilLog.log.error(exc.getStackTrace());
            throw new CriptException();
       }
    }
    
    public String desencriptar(String cadena) throws CriptException {
        try {
            byte[] decoder = new sun.misc.BASE64Decoder().decodeBuffer(cadena);

            byte[] utf8 = dcipher.doFinal(decoder);

            return new String(utf8, "UTF8");
        } catch (Exception exc) {
            UtilLog.log.error(exc.getStackTrace());
            throw new CriptException();
       }
    }
}
